<?php

namespace App\Http\Controllers\Wechat;


use App\Http\Controllers\ScoreRuleController;
use App\Models\BindLog;
use App\Models\BookTypes;
use App\Models\HotSearch;
use App\Models\UserInfo;
use App\Validate\LibInfoValidate;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 图书馆对接接口信息
 */
class LibInfoController extends CommonController
{
    public $libapiObj = null;
    public $validate = null;
    public function __construct()
    {
        parent::__construct();

        $this->validate = new LibInfoValidate();
        $this->libapiObj = $this->getLibApiObj();
    }


    /**
     * 绑定读者证  或密码错误重新登录
     * @param $authorrization ：用户 token
     * @param account 读者证号
     * @param password 读者证密码
     */
    public function bingReaderId()
    {
        $account = $this->request->account;
        $password = $this->request->password;

        $user_id = $this->request->user_info['id'];

        //增加验证场景进行验证
        if (!$this->validate->scene('bing_reader')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否绑定了读者证
        $userInfoModel = new UserInfo();
        $user_info = $userInfoModel->where('id', $user_id)->first();
        //因为可能是密码错误。这个不判断
        // if (!empty($user_info['account_id'])) {
        //     return $this->returnApi(202, "您已绑定其他读者证，请勿重复绑定");
        // }

        $res = $this->libapiObj->login($account, $password);

        if ($res['code'] === 200) {
            //登录成功
            DB::beginTransaction();
            try {
                $account = $res['content']['account']; //重新赋值账号，因为有可能是身份证登录的

                $userLibraryInfoModel = new UserLibraryInfo();
                $result = $userLibraryInfoModel->where('account', $account)->first();

                $first_bind = $result; //用这个判断是否已经绑定过

                $res['content']['password'] = $password;

                if ($result) {
                    //判断此读者证是否被其他用户绑定
                    $isBindAccount = $userLibraryInfoModel->isBindAccount($result->id, $user_id);
                    if ($isBindAccount !== true) {
                        throw new \Exception($isBindAccount, 2002);
                    }

                    $qr_url = $userLibraryInfoModel->change($res['content'], $result);
                    $account_id = $result->id;
                } else {
                    $qr_url = $userLibraryInfoModel->change($res['content']);
                    $account_id = $userLibraryInfoModel->id;
                }

                //绑定在用户信息里面
                if (empty($user_info['account_id'])) {
                    //修改读者证号二维码
                    $userInfoModel->where('id', $user_id)->update([
                        'account_id' => $account_id,
                        'qr_url' => $qr_url,
                        'bind_time' => date('Y-m-d H:i:s')
                    ]);

                    //添加绑定日志
                    $bindLogModel = new BindLog();
                    $bindLogModel->add([
                        'user_id' => $user_id,
                        'account' => $account,
                        'password' => $password,
                        'state' => 1,
                    ]);
                } elseif ($user_info['account_id'] != $account_id) {
                    throw new Exception('您已绑定其他读者证号，请勿重复绑定！', 2002);
                }

                //是否第一次绑定读者证
                if (config('other.is_need_score') === true && empty($first_bind)) {
                    $scoreRuleObj = new ScoreRuleController();
                    $score_status = $scoreRuleObj->checkScoreStatus(1, $user_id, $account_id);
                    if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);

                    if ($score_status['code'] == 200) {
                        $system_id = $this->systemAdd($score_status['score_info']['type_name'], $user_id, $account_id, 1, 0, $score_status['score_info']['intro']);
                        $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, $system_id); //添加积分消息
                    }

                    $invite_user_info = $userInfoModel->where('id', $user_id)->first();
                    //增加邀请人的积分
                    if (!empty($invite_user_info['invite_user_id']) || !empty($invite_user_info['invite_account_id'])) {
                        $invite_account_id = $invite_user_info['invite_account_id'];
                        //从新获取读者证id
                        if (empty($invite_account_id)) {
                            $invite_account_id = $userInfoModel->where('id', $invite_user_info['invite_user_id'])->value('account_id');
                        }
                        if (!empty($invite_account_id)) {
                            $score_status = $scoreRuleObj->checkScoreStatus(3, $invite_user_info['invite_user_id'], $invite_account_id);
                            if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);

                            if ($score_status['code'] == 200) {
                                $system_id = $this->systemAdd($score_status['score_info']['type_name'], $invite_user_info['invite_user_id'], $invite_user_info['invite_account_id'], 12, 0, $score_status['score_info']['intro']);
                                $scoreRuleObj->scoreChange($score_status, $invite_user_info['invite_user_id'], $invite_user_info['invite_account_id'], $system_id); //添加积分消息
                            }
                        }
                    }
                }
                DB::commit();
                return $this->returnApi(200, '绑定成功', true);
            } catch (\Exception $e) {
                $msg = $e->getCode() == 2002 ? $e->getMessage() : '绑定失败';
                DB::rollBack();
                return $this->returnApi(202, $msg);
            }
        } else {
            return $this->returnApi(207, $res['msg'] ? $res['msg']  : "读者证号或密码不正确");
        }
    }

    /**
     * 解除绑定读者证
     * @param @param $authorrization ：用户 token
     */
    public function unBindReaderId()
    {
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $res = UserInfo::find($user_id);
        if (empty($res)) {
            return $this->returnApi(202, '信息获取失败');
        }
        if (empty($res['account_id'])) {
            return $this->returnApi(202, '网络错误');
        }

        DB::beginTransaction();
        try {
            $res->account_id = null;
            $res->qr_url = null;
            $res->bind_time = date('Y-m-d H:i:s');
            $res->save();

            BindLog::where('user_id', $user_id)->where('state', 1)->update(['state' => 2, 'change_time' => date('Y-m-d H:i:s')]);

            //修改掉之前的二维码
            // if ($res->qr_url) {
            //     @unlink(config('other.img_addr') . $res->qr_url);
            // }

            DB::commit();
            return $this->returnApi(200, '解除绑定成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '解除绑定失败');
        }
    }

    /**
     * 修改读者证密码
     * @param @param $authorrization ：用户 token  必须要绑定读者证
     * @param $old_password  读者旧密码
     * @param $new_password  读者新密码
     */
    public function changePwd()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change_password')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $old_password = $this->request->old_password;
        $new_password = $this->request->new_password;

        $account_info = UserLibraryInfo::select('id', 'account')->find($account_id);
        if (empty($account_info)) {
            return $this->returnApi(201, "网错错误");
        }

        //验证读者证号密码是否正确
        $res = $this->libapiObj->login($account_info->account, $old_password);
        if ($res['code'] != 200) {
            return $this->returnApi(201,  $res['msg']);
        }

        //验证旧密码是否正确,验证通过后修改密码
        $res = $this->libapiObj->changeReader($account_info->account, ['rdpasswd' => $new_password]);

        if ($res['code'] === 200) {
            return $this->returnApi(200, "修改成功", true);
        } else {
            return $this->returnApi(202, $res['msg']);
        }
    }


    /**
     * 读者证延期
     * @$account_id 用户id    必须要绑定读者证
     */
    public function cardDelay()
    {
        $user_id = request()->user_id;
        $account_id = $this->request->user_info['account_id'];

        //判断读者证号密码是否正确 和是否绑定读者证
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id, $account_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        $res = $this->libapiObj->manageReader($account_lib_info['account'], 8);
        if ($res['code'] === 200) {
            //修改截止时间
            $userLibraryInfoModel->where('id', $account_lib_info['id'])->update(['end_time' => $res['content']['end_time']]);

            $data['account'] = $res['content']['account'];
            $data['beg_time'] = $res['content']['start_time'];
            $data['end_time'] = $res['content']['end_time'];

            return $this->returnApi(200, "读者证延期成功", true, $data);
        }
        return $this->returnApi(202, $res['msg'] ? $res['msg'] : "读者证延期失败");
    }

    /**
     * 读者证挂失操作
     * @user_id 用户id    必须要绑定读者证
     */
    public function lost()
    {
        $user_id = request()->user_id;
        $account_id = $this->request->user_info['account_id'];

        //判断读者证号密码是否正确 和是否绑定读者证
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id, $account_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        $res = $this->libapiObj->manageReader($account_lib_info['account'], 3);

        if ($res['code'] === 200) {
            $userLibraryInfoModel->where('id', $account_id)->update(['status_card' => '挂失']);

            //修改截止时间
            return $this->returnApi(200, "挂失成功", true);
        }
        return $this->returnApi(202, "挂失失败");
    }

    /**
     * 读者证恢复
     * @user_id 用户id    必须要绑定读者证
     */
    public function lostRecover()
    {
        $user_id = request()->user_id;
        $account_id = $this->request->user_info['account_id'];

        //判断读者证号密码是否正确 和是否绑定读者证
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id, $account_id, '挂失');
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        $res = $this->libapiObj->manageReader($account_lib_info['account'], 1);

        if ($res['code'] === 200) {
            $userLibraryInfoModel->where('id', $account_id)->update(['status_card' => '有效']);

            //修改截止时间
            return $this->returnApi(200, "恢复成功", true);
        }
        return $this->returnApi(202, "恢复失败");
    }


    /**
     * 获取借阅记录列表
     * @param $authorrization 用户 token    例：Bearer 1可选
     * @param type int 1 当前借阅  2 历史借阅记录
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time 借阅开始日期   当前借阅  不需要此参数
     * @param end_time 借阅结束日期    当前借阅  不需要此参数
     */
    public function getBorrowList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_borrow_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account =  $account_lib_info['account'];

        if ($this->request->type == 1) {
            $res = $this->libapiObj->getNowBorrowList($account, $page, $limit);
        } else {
            $res = $this->libapiObj->getReturnData($account, $page, $limit, $start_time, $end_time);
        }

        //增加行为分析
        // $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        // $appInviteCodeBehaviorModel->add(25);

        if ($res['code'] == 200) {
            // foreach ($res['content'] as $key => $val) {
            //     $res['content'][$key]['lib_name'] = config('other.lib_name');
            // }
            return $this->returnApi(200, '获取成功', true, $res['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取检索信息列表
     * @param keywords_type string 检索类型 all 任意词
     *                              title 书名
                                   author 作者
                                   classno 分类号
                                   isbn isbn号
                                   callno 索书号
     * @param keywords string 检索信息
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function getBookInfoList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('search_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $res = $this->libapiObj->getBookInfo($keywords, $keywords_type, "dim", 'desc', $page, $limit);

        if ($res['code'] == 200) {
            //添加检索热词
            if (!empty($keywords)) {
                $hotSearchModel = new HotSearch();
                $hotSearchModel->hotSearchAdd($keywords, 3);
            }

            return $this->returnApi(200, '获取成功', true, $res['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取馆藏书籍详情
     * @param metaid 图书在图书馆的id
    // * @param metatable 书目库
     */
    public  function getLibBookDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('lib_book_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $metaid = $this->request->metaid;
        // $metatable = $this->request->metatable;

        $book_info = $this->libapiObj->getBookDetail($metaid);
        if ($book_info['code'] == 200) {
            if (!empty($book_info['content']['classno'])) {
                $classify = substr($book_info['content']['classno'], 0, 1);
                $type_name = BookTypes::where('classify', $classify)->value('title');
                $book_info['content']['type_name'] = $type_name ? $type_name : '暂无分类';
            } else {
                $book_info['content']['type_name'] = '暂无分类';
            }

            //默认接口是不返回封面的
            $book_info['content']['img'] = !empty($book_info['content']['img']) ? $book_info['content']['img'] : 'default/default_book.png';
            $book_info['content']['bar_code_info'] = $book_info['content']['holdings'];
            unset($book_info['content']['holdings']);

            return $this->returnApi(200, '获取成功', true, $book_info['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }



    /**
     * 在线续借
     * @param token string 用户token
     * @param content json  格式数据 [{"book_name":1,"barcode":11,"author":1},{"book_name":1,"barcode":11,"author":1}]
     *                      数组格式 [['book_name'=>1,'barcode'=>11,'author'=>1],['book_name'=>1,'barcode'=>11,'author'=>1]]
     */
    public function renewBook()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('renew')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $account = $this->request->user_info['account'];
        $content = $this->request->content;

        $content = json_decode($content, true);

        $msg = '';
        foreach ($content as $key => $val) {
            $res = $this->libapiObj->renewBook($account, $val['barcode']);

            $msg .= '【' . $val['book_name'] . '】' . $res['msg'] . '；'; //$res['msg'] 自带一个分号

            if ($res['code'] == 200) {
                $this->systemAdd('续借成功', $user_id, $account_id, 38, null, '【' . $val['book_name'] . '】,续借成功！');

                if (config('other.is_send_wechat_temp_info')) {
                    $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                    $data['openid'] = UserWechatInfo::getOpenIdByUserId(request()->user_info['id']);
                    $data['msg'] = '续借成功，请在规定时间内归还！';

                    // if($result['type'] == 1){
                    //     $book_info = ShopBook::where('id' , $result['book_id'])->first();
                    // }else{
                    //     $book_info = LibBook::where('id' , $result['book_id'])->first();
                    // }
                    $data['book_name'] = $val['book_name'];
                    $data['author'] = $val['author'];
                    $data['return_time'] = $res['content']['messagelist'][0]['returndate'];
                    // $data['number'] = !empty($res['content']['renew']) ? $res['content']['renew'] : (!empty($res['content']['renewNum']) ? $res['content']['renewNum'] : 1);
                    $data['number'] = 1;
                    $tempInfoObj->sendTempInfoRenewSuccess($data);
                }
            }
        }
        return $this->returnApi(200, $msg, true);
    }


    /**
     * 馆藏检索热词列表
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function hotLibSearchList()
    {
        // if (!$this->validate->scene('hot_search_list')->check($this->request->all())) {
        //     return $this->returnApi(201,  $this->validate->getError());
        // }

        $type = 3;
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        $res = HotSearch::select('content')
            ->where('type', $type)
            ->orderByDesc('number')
            ->paginate($limit)
            ->toArray();


        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(13);

        if ($res['data']) {
            //增加排名
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['rank'] = ($page - 1) * $limit + $key + 1;
            }

            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
}
